<template>
	<view :style="skin" class="content home">
		<StatusBarHeight bgColor="var(--subjectColor)" />
		<view class="headBox">
			<view class="moneyInfo" @click="skipBalance">
				<view class="topUp">
					<text>{{$t('lease.topUp')}}</text>
					<!-- <view>{{isNoNetWork?'离线中':'在线中'}}</view> -->
				</view>
				<view class="moneyBox">
					<view>
						{{$t('lease.onlineBalance')}}
					</view>
					<view>
						{{moneyTran(moneyObj.onMoney) }} {{$t('lease.unit')}}
					</view>
				</view>

				<view class="moneyBox">
					<view>
						{{$t('lease.offlineBalance')}}
					</view>
					<view>
						{{moneyTran(moneyObj.offMoney) }} {{$t('lease.unit')}}
					</view>
				</view>
				<view class="moneyBox">
					<view>
						{{$t('lease.revenue')}}
					</view>
					<view>
						{{moneyTran(moneyObj.amountTurnover)}}{{$t('lease.unit')}}
					</view>
				</view>

			</view>
		</view>
		<view class="search">
			<navigator url="/pages/home/searchUser/searchUser">
				<view class="searchInput">
					<text class="iconfont icon-a-mingchengsearch"></text>
					<view class="">
						{{$t('lease.memberName')}}
					</view>
				</view>
			</navigator>

			<view class="huiyuanzc flex-c-SB-c" @click="vipRegister">
				<view class="imgBox">
					<image src="../../static/images/huiyuan.png" mode=""></image>
				</view>
				{{$t('lease.memRegistration')}}
			</view>
		</view>
		<view class="tabs">
			<u-tabs :activeStyle="{
						color: '#303133',
						fontWeight: 'bold',
						transform: 'scale(1.2)'
					}" :list="list" @click="clickTabs" :scrollable="false" :current="current"></u-tabs>
		</view>

		<view class="homeMain">
			<!-- 租赁 -->
			<lease @updateDeviceType="updateDeviceType" @alseMoney="alseMoney" @updOffMoney="updOffMoney" :moneyObj="moneyObj"
				:selectDeviceInfo="selectDeviceInfo" v-if="current === 0" />
			<!-- 归还 -->
			<giveBack @updateDeviceType="updateDeviceType" v-else-if="current === 1" />
			<!-- 可租 -->
			<tenantable v-else-if="current === 2" @handleRent="handleRent" :deviceTypeList="deviceTypeList" />
			<!-- 逾期 -->
			<overdue pageType="home" v-else-if="current === 3" :overdueList="overdueList" :overdueIds="overdueIds"
				@getoverList="getoverList" />
		</view>

		<customtabbar tabbarIndex="0" />
	</view>
</template>
<script>
	import customtabbar from '@/components/custom-tab-bar.vue'
	import StatusBarHeight from '@/components/StatusBarHeight.vue'
	import lease from './lease.vue'
	import giveBack from './giveBack.vue'
	import tenantable from './tenantable.vue'
	import overdue from './overdue.vue'


	import {
		mapState,
	} from 'vuex'
	import {
		getLease,
		addLease,
		getNoSyncLease,
		setSyncDate,
	} from '@/utils/sql/sqllease.js'
	import {
		getDeviceType,
	} from '@/utils/sql/sqlDeviceType.js'
	import {
		addDevice
	} from '@/utils/sql/sqlDevice.js'
	import {
		getMoneyInfo,
		addOrUpdateMoney
	} from '@/utils/sql/sqlMoney.js'
	import {
		getUserToId,
		addUser,
		getUserAll
	} from '@/utils/sql/sqlUser.js'
	import {
		deepClone,
		formatDateTime,
		encryption,
		setSyncDevice
	} from '@/utils/index.js'
	import {
		lostReport,
	} from '@/api/leaProductLost.js'
	import {
		getOffMoney,
		delOffMoney
	} from '@/utils/sql/sqloffLineDtoList.js'
	import {
		getInCome,
		delInCome
	} from '@/utils/sql/sqlInComeDtoList.js'
	import {
		delTrunOver,
		getTrunOver
	} from '@/utils/sql/sqlTrunoverDtoList.js'
	import {
		leaSyn,
	} from '@/api/leaData.js'
	import {
		getPassConfig,
		delDBpassConfig
	} from '@/utils/sql/sqlPassConfig.js'
	import {
		ckDetails
	} from '@/api/deviceCheck.js'
	import {
		getInStoreAll
	} from '@/utils/sql/sqlDevice.js'
	const database = uni.getStorageSync('database');
	export default {
		data() {
			return {
				userArr: [],
				getDate: false,
				overdueIds: [],
				isNoNetWork: false,
				deviceTypeList: [], //可租列表
				overdueList: [],
				selectDeviceInfo: {}, //可租组件选择的设备
				current: 0,
				moneyObj: {},
				list: [{
						name: this.$t('lease.rental')
					},
					{
						name: this.$t('lease.return')
					},
					{
						name: this.$t('lease.tenantable')
					},
					{
						name: this.$t('lease.overdue')
					}
				],
			}
		},
		async onShow() {
			this.getNetWork()

			uni.hideTabBar({
				animation: false
			})
			// 本地数据库
			await this.openDB()
			await this.getDBuser()
			// 获取品类列表
			await this.getDeviceTypeList()
			// 获取租赁列表
			await this.getlist()
			// 获取用户金额信息
			await this.getUserMoney()

			ckDetails().then(async res => {
				let uRes = await getInStoreAll();
				// 调试
				if (res.code == 5 && uRes.data.length > 0) {
					uni.switchTab({
						url: '/pages/property/property'
					})
					uni.setStorageSync('uncounted', true)
				} else {
					uni.setStorageSync('uncounted', false)
				}

			})

			let inSDevice = uni.getStorageSync('inSDevice')
			if (inSDevice) {
				this.current = 0
				this.selectDeviceInfo = inSDevice
				uni.removeStorageSync('inSDevice')
			}


		},
		onReady() {
			let that = this
			let color = this.$store.getters.getSkinColor('--moduleColor')
			uni.setNavigationBarColor({
				frontColor: '#000000',
				backgroundColor: color
			})
		},
		methods: {
		
			async getDBuser() {
				let res = await getUserAll();
				this.userArr = res.data
			},
			moneyTran(m) {
				return (m / 100).toFixed(2)
			},
			// 修改我的余额
			updOffMoney(num, network, commission) {
				if (network == 'on') { //在线
					let onMoney = parseInt(this.moneyObj.onMoney) - parseInt(num)
					this.moneyObj.onMoney = onMoney
				} else {
					let offMoney = parseInt(this.moneyObj.offMoney) - parseInt(num)
					this.moneyObj.offMoney = offMoney
				}


				let amountTurnover = parseInt(this.moneyObj.amountTurnover) + parseInt(num)
				let amountIncome = parseInt(this.moneyObj.amountIncome) + parseInt(num * (commission / 100))
				this.moneyObj.amountTurnover = amountTurnover
				this.moneyObj.amountIncome = amountIncome


				addOrUpdateMoney(this.moneyObj)
			},
			// 返还我的余额
			alseMoney(num, network) {
				if (network == 'on') { //在线
					let onMoney = parseInt(this.moneyObj.onMoney) + parseInt(num)
					this.moneyObj.onMoney = onMoney
				} else {
					let offMoney = parseInt(this.moneyObj.offMoney) + parseInt(num)
					this.moneyObj.offMoney = offMoney
				}


				let amountTurnover = parseInt(this.moneyObj.amountTurnover) - parseInt(num)

				this.moneyObj.amountTurnover = amountTurnover


				addOrUpdateMoney(this.moneyObj)
			},

			getNetWork() {
				let that = this
				// 获取
				uni.getNetworkType({
					success: async res => {
						if (res.networkType == 'none') {
							uni.setStorageSync('isNoNetWork', true) //表示当前无网络
							that.isNoNetWork = true
						} else {
							uni.setStorageSync('isNoNetWork', false)
							that.isNoNetWork = false
						}
					},

				})

				// 监听网络变化
				uni.onNetworkStatusChange(async function(res) {
					if (!res.isConnected) {
						uni.setStorageSync('isNoNetWork', true)
						that.isNoNetWork = true
					} else {
						uni.setStorageSync('isNoNetWork', false)
						that.isNoNetWork = false
					}
				});
			},
			async syncMoney(skipBalancePage) { //同步金钱
				uni.showLoading({
					title: this.$t('me.SyncingData'),
					icon: 'loading',
				})
				let offRes = await getOffMoney();
				let inRes = await getInCome();
				let overRes = await getTrunOver();

				let mRes = await getMoneyInfo();

				let syncData = {
					data: {
						amountIncome: null,
						amountOffline: null,
						amountTurnover: null,
						synAmountIncomeDtoList: null,
						synAmountOfflineDtoList: null,
						synAmountTurnoverDtoList: null,
					},
					synOpe: 'amount'
				}

				if (offRes.data.length > 0) {
					let offResLen = offRes.data.length - 1;
					syncData.data.amountOffline = mRes.data[0].offMoney;
					// syncData.data.amountOffline = offRes.data[offResLen].offlineAmountAll;
					syncData.data.synAmountOfflineDtoList = offRes.data
				}

				if (inRes.data.length > 0) {
					let inResLen = inRes.data.length - 1;
					syncData.data.amountIncome = mRes.data[0].amountIncome;
					// syncData.data.amountIncome = inRes.data[inResLen].incomeAmountAll;
					syncData.data.synAmountIncomeDtoList = inRes.data
				}

				if (overRes.data.length > 0) {
					let overResLen = overRes.data.length - 1;
					syncData.data.amountTurnover = mRes.data[0].amountTurnover;
					// syncData.data.amountTurnover = overRes.data[overResLen].turnoverAmountAll;
					syncData.data.synAmountTurnoverDtoList = overRes.data
				}


				let res = await leaSyn({
					edata: encryption(JSON.stringify(syncData))
				})
				if (res.code == 0) {

					this.delSqlMoney()
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: this.$t('me.SyncDatasucc'),
							icon: 'success'
						})

						setTimeout(() => {
							this.syncDevice(skipBalancePage)
						}, 1000)
					}, 1000)


				} else {
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: res.msg,
							icon: 'error'
						})
					}, 1000)

				}
			},
			// 同步设备的 租赁 归还 逾期
			async syncDevice(skipBalancePage) {
				// 获取所有未同步的数据
				let leaRes = await getNoSyncLease();

				let syncArr = setSyncDevice(leaRes.data)

				if (syncArr.length == 0) {
					uni.showToast({
						title: this.$t('me.Nodevicesync'),
						icon: 'none'
					})
					this.syncDeviceInfo()
					skipBalancePage()
					return false
				}
				uni.showLoading({
					title: this.$t('me.SyncingDevice'),
					icon: 'loading',
				})
				let promiseAll = []
				syncArr.forEach(async item => {
					let syncData = {
						data: item,
						"synOpe": "lease"
					}

					promiseAll.push(leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}))
					// 租赁信息变为已经同步了
					setSyncDate(item.pid);
				})
				console.log(promiseAll);
				Promise.all(promiseAll).then(results => {
					let result = results.every(ele => ele.code == 0);
					if (result) {
						uni.hideLoading();
						uni.showToast({
							title: this.$t('me.SyncDevicesucc'),
							icon: 'success'
						})

						//从云端同步设备数据下拉，应对设备释放，和在库设备在别的代理商入库
						this.syncDeviceInfo();
						skipBalancePage()
					} else {
						let err = results.find(e => {
							return e.code != 0
						})
						setTimeout(() => {
							uni.hideLoading();
							uni.showToast({
								title: err.msg,
								icon: 'error'
							})
						})
					}
				}).catch(error => {
					console.log(error, '错误')
				})
			},
			//后台释放账号，APP做的同步操作  入库了这个代理商的设备， 需要同步数据
			async syncDeviceInfo() {
				let res4 = await getNoSyncLease();
				let res4Len = res4.data.length;
				if (res4Len == 0) { //只有本地没有要同步的数据才会同步云端设备

					let dbRes = await getInStoreArr();
					let serRes = await liststockbind();

					let dbArr = dbRes.data == null ? [] : dbRes.data
					let serArr = serRes.data == null ? [] : serRes.data
					console.log(dbArr);
					console.log(serArr);

					// 丢失找回后改变状态 数据长度是相同的，只是状态不同
					if (dbArr.length == serArr.length) {
						serArr.map(item1 => {
							dbArr.map(item2 => {
								if (item1.productId == item2.productId && item2.stockStatus == 8 && item1.stockStatus == 1) {
									console.log(item1);
									addDevice({
										productId: item1.productId,
										stockStatus: 1
									})
									addInsoter(item1.productModel);
									addTenantable(item1.productModel);
								}
							})
						})
					}

					let filteredArr = dbArr.filter(dbItem => {
						return !serArr.some(serveItem => {
							return serveItem.productId === dbItem.productId;
						});
					});
					uni.hideLoading()
					console.log(filteredArr);
					filteredArr.forEach(async item => {
						if (item.stockStatus == 4 || item.stockStatus == 6 || item.stockStatus == 8 || item.stockStatus ==
							10) { //本地多余的数据状态 如果是租赁总或者逾期 去除lease表中的数据
							await delLeasePid(item.productId)
						}
						await delPid(item.productId)

						if (item.stockStatus == 1) { //修改可以租赁的值
							await reduceInsoter(item.productModel);
							await reduceTenantable(item.productModel);
						}

					})
				}

			},
			syncPass() {
				getPassConfig().then(res => {
					let syncData = {
						"synOpe": "sec",
						data: res.data
					}
					leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}).then(res => {
						if (res.code == 0) {
							delDBpassConfig()
						}
					})

				})
			},
			// 同步完成之后，删除本地金额数据
			delSqlMoney() {
				delOffMoney()
				delInCome()
				delTrunOver()
			},
			async skipBalance() {
				let netWork = uni.getStorageSync('isNetWork');
				console.log(netWork);
				if (netWork) {
					uni.showToast({
						title: 'No Network',
						icon: 'none',
						duration: 2000
					})
					return false
				}

				await this.syncMoney(this.skipMoney)

				await this.syncPass()
			},
			skipMoney() {
				uni.navigateTo({
					url: '/pagesBalance/myBalance/myBalance'
				})
			},
			// 获取用户的金额
			getUserMoney() {
				getMoneyInfo().then(res => {
					this.moneyObj = res.data[0]
				})
			},
			updateDeviceType() {
				this.getlist()
				this.getDeviceTypeList()
			},
			// 可租列表
			async getDeviceTypeList() {
				let res = await getDeviceType()
				if (res.code == 0) {
					let overNum = 0
					res.data.forEach(item => {
						let renNum = parseInt(item.tenantable)
						overNum += ((renNum > 0 ? renNum : 0) || 0)
					})
					this.deviceTypeList = res.data
					this.list.map((item, index) => {
						if (index == 0) {
							return item.name = `${this.$t('lease.rental')}`
						}
					})
					this.list.map((item, index) => {
						if (index == 1) {
							return item.name = `${this.$t('lease.return')}`
						}
					})

					this.list.map((item, index) => {
						if (index == 2) {
							return item.name = `${this.$t('lease.tenantable')}(${overNum})`
						}
					})

					this.list.map((item, index) => {
						if (index == 3) {
							return item.name = `${this.$t('lease.overdue')}(${this.overdueList.length})`
						}
					})


				}
			},
			getoverList() {
				getLease().then(res => {
					this.overdueList = res.data.filter(item => {
						return item.leaseStatus == 6
					})
					this.overdueIds = []
				})
			},
			// 租赁逾期
			getlist() {
				let newDate = new Date().getTime()
				getLease().then(res => {
					console.log(res);
					if (res.code == 0) {


						// 设置逾期状态和逾期时间

						res.data.map(item => {
							let day = parseInt((newDate - item.expirationTime) / (60 * 60 * 1000));

							if (item.expirationTime == '') {
								return false
							}
							if (item.expirationTime <= newDate && item.leaseStatus == 4) {
								//设置用户的逾期总次数
								if (item.remind == 0) {
									getUserToId(item.customerAccount).then(res => {
										let obj = {
											customerAccount: item.customerAccount,
											overdueNum: (parseInt(res.data[0].overdueNum) + 1).toString()
										}
										addUser(obj)
									})
								}
								return item.leaseStatus = 6, item.overdueDay = day
							}

							if (item.leaseStatus == 6) {
								console.log(day);
								return item.overdueDay = day
							}
						})



						// 逾期超过48H转丢失
						res.data.map(item => {
							// 调试
							if (item.overdueDay >= 48 && item.leaseStatus == 6) {
								lostReport({
									productModel: item.productModel,
									productId: item.productId,
									lostCustomerAccount: item.customerAccount,
									lostReason: 'Not returned for more than 48 hours',
								});
								
								addDevice({
									productId: item.productId,
									stockStatus: 8
								})
								return item.leaseStatus = 8, item.iSync = 0
							}
						})

						res.data.map(item => {
							let index = this.userArr.findIndex(ele => {
								return ele.customerAccount == item.customerAccount
							});
							return item.rentNum = this.userArr[index].rentNum, item.overdueNum = this.userArr[index].overdueNum
						})

						this.overdueList = res.data.filter(item => {
							return item.leaseStatus == 6
						})



						res.data.forEach(async rrs => {
							await addLease(rrs)
						})
						let overIdsList = []
						res.data.forEach(item => {
							// 控制逾期弹框
							if (item.nextPopupTime <= newDate && (item.remind < 3 || item.remind == 'null') && item
								.leaseStatus == 6) {
								let remind = item.remind == 'null' ? 0 : item.remind

								overIdsList.push({
									leaseId: item.leaseId,
									expirationTime: item.expirationTime,
									remind: remind,
									nextPopupTime: item.nextPopupTime
								});
								
								addDevice({
									productId: item.productId,
									stockStatus: 6
								})
							}

						})

						// 最后设置修改的数据
						this.overdueIds = overIdsList

						if (this.overdueIds.length > 0) {
							this.current = 3
						}

						this.list.map((item, index) => {
							if (index == 3) {
								return item.name = `${this.$t('lease.overdue')}(${this.overdueList.length})`
							}
						})


					}
				})
			},
			async openDB() {

				let res = await this.$sql.isOpen(database);
				console.log(res);
				if (res.data) return
				let res1 = await this.$sql.openDB(database);
				console.log(res1);

			},
			skipsqlite() {
				uni.navigateTo({
					url: '/pages/home/sqlitePage/sqlitePage'
				})
			},
			clickTabs(item) {

				this.current = item.index
			},
			// 选择了要租赁的设备
			handleRent(item) {
				console.log(11);
				this.current = 0
				this.selectDeviceInfo = item
			},

			vipRegister() {
				let netWork = uni.getStorageSync('isNetWork');
				console.log(netWork);
				if (netWork) {
					uni.showToast({
						title: 'No Network',
						icon: 'none',
						duration: 2000
					})
					return false
				}
				uni.navigateTo({
					url: '/pages/login/mobileRegister/mobileRegister?type=2'
				})
			}
		},
		computed: {
			...mapState({
				skin: state => state.theme.skin,

			})

		},
		components: {
			customtabbar,
			StatusBarHeight,
			lease,
			giveBack,
			tenantable,
			overdue
		}
	}
</script>
<style lang="scss" scoped>
	.home {
		.headBox {
			width: 100%;
			height: 88px;
			background-color: var(--subjectColor);
			padding: 8px 16px;
			box-sizing: border-box;

			.moneyInfo {
				width: 100%;
				height: 72px;
				background-color: #FFBF6B;
				display: flex;
				align-items: center;
				justify-content: space-evenly;
				border-radius: 8px;

				.topUp {
					font-size: 24px;
					font-weight: 600;
				}

				.moneyBox {
					font-size: 14px;
				}
			}
		}

		.search {
			width: 100%;
			height: 56px;
			margin-bottom: 8px;
			display: flex;
			display: flex;
			align-items: center;
			justify-content: space-evenly;

			.searchInput {
				width: 278px;
				height: 44px;
				border-radius: 27px;
				box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.4);
				display: flex;
				flex-direction: row;
				align-items: center;
				padding-left: 16px;
				box-sizing: border-box;
			}
		}

		.huiyuanzc {

			.imgBox {
				width: 24px;
				height: 24px;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.homeMain {
			margin-top: 8px;
			width: 100%;
			height: calc(100% - 250px);
			box-sizing: border-box;
		}
	}
</style>